<template>
  <div>
    <el-page-header @back="$router.back()" :content="$route.name"/>
    <el-main style="margin-top: 20px">
      <el-form :inline="true" :model="addAddrForm" status-icon
               :rules="rules" ref="addAddrForm" class="demo-form-inline">
        <el-form-item label="添加地址"/>
        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model.number="addAddrForm.contactNumber"/>
        </el-form-item>
        <el-form-item label="省份">
          <el-select v-model="addAddrForm.province" prop="province" placeholder="请选择">
            <el-option
                v-for="item in provinceList"
                :key="item.value"
                :value="item.value"
                :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="确切地址" prop="exactAddr">
          <el-input v-model="addAddrForm.exactAddr"></el-input>
        </el-form-item>
        <el-form-item style="padding-right: 0">
          <el-button type="primary" @click="add" :disabled="addButton">添加</el-button>
          <el-button @click="resetForm('addAddrForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-main>
    <el-table :data="data" border>
      <el-table-column prop="id" label="编号" width="150"/>
      <el-table-column prop="contactNumber" label="联系电话" width="150"/>
      <el-table-column prop="province" label="省份" width="150"/>
      <el-table-column prop="exactAddr" label="确切地址"/>
      <el-table-column fixed="right" label="操作" width="110">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="medium"
                     @click="updateIt(scope.row)" circle/>
          <el-button type="danger" icon="el-icon-delete" size="medium"
                     @click="removeIt(scope.row)" circle/>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="修改地址"
               :visible.sync="dialogFormVisible"
               @open="updateButton=false">
      <el-form :model="updateAddrForm" status-icon
               :rules="rules" ref="updateAddrForm"
               label-position="left">
        <el-form-item label="id" label-width="80px">{{updateAddrForm.id}}</el-form-item>
        <el-form-item label="联系电话" prop="contactNumber" label-width="80px">
          <el-input v-model.number="updateAddrForm.contactNumber"></el-input>
        </el-form-item>
        <el-form-item label="省份" label-width="80px">
          <el-select v-model="updateAddrForm.province">
            <el-option
                v-for="item in provinceList"
                :key="item.value"
                :value="item.value"
                :label="item.label">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="确切地址" prop="exactAddr" label-width="80px">
          <el-input v-model="updateAddrForm.exactAddr"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="update"
                   :disabled="updateButton">修改
        </el-button>
        <el-button @click="()=>{this.dialogFormVisible = false;
                resetForm('updateAddrForm')}">取消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "MyAddr",
  methods: {
    getData() {
      const user = this.$store.state.user
      this.$axios.get(this.$serverUrl
          + '/addr/list?ownerId=' + user.id)
          .then(response => {
            this.data = response.data
            console.log(response.data)
          })
          .catch(error => {
            console.log(error)
          })
    },
    message(msg, bool) {
      this.$message({
        showClose: true,
        message: msg + (bool ? '成功!' : '失败!'),
        type: (bool ? 'success' : 'error')
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    updateIt(item) {
      // console.log(item)
      let p = 11;
      this.provinceList.forEach(province => {
        if (item.province === province.label) {
          p = province.value
        }
      })
      this.updateAddrForm = {
        id: item.id,
        contactNumber: Number.parseInt(item.contactNumber),
        province: p,
        exactAddr: item.exactAddr
      }
      // console.log(this.updateAddrForm)
      this.dialogFormVisible = true
    },
    removeIt(item) {
      this.$confirm('此操作将永久删除该地址, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.remove(item.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    add() {
      this.$refs['addAddrForm'].validate((valid) => {
        if (valid) {
          this.addButton = true
          const user = this.$store.state.user
          this.addAddrForm.owner = user.id
          this.$axios.post(this.$serverUrl
              + '/addr/add', this.addAddrForm)
              .then(response => {
                this.addAddrForm = {
                  contactNumber: '',
                  province: 11,
                  exactAddr: ''
                }
                this.message('添加', response.data)
                this.getData()
                this.addButton = false
              })
              .catch(error => {
                console.log(error)
                this.addButton = false
              })
        }
      })
    },
    update() {
      this.$refs['updateAddrForm'].validate((valid) => {
        if (valid) {
          this.updateButton = true
          this.$axios.put(this.$serverUrl
              + '/addr/update', this.updateAddrForm)
              .then(response => {
                console.log(response.data)
                this.message('修改', response.data)
                this.getData()
                this.dialogFormVisible = false
              })
              .catch(error => {
                console.log(error)
              })
        }
      })
    },
    remove(id) {
      this.$axios.delete(this.$serverUrl
          + '/addr/delete?id=' + id)
          .then(response => {
            this.message('删除', response.data)
            this.getData()
          })
          .catch(error => {
            console.log(error)
          })
    }
  },
  data() {
    return {
      data: this.getData(),
      provinceList: this.$store.state.provinceList,
      addAddrForm: {
        contactNumber: '',
        province: 11,
        exactAddr: ''
      },
      addButton: false,
      updateButton: false,
      dialogFormVisible: false,
      updateAddrForm: {},
      rules: {
        contactNumber: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入联系电话'));
              } else {
                if (!Number.isInteger(value)) {
                  console.log(value)
                  console.log(!Number.isInteger(value))
                  callback(new Error('联系电话必须为数字值'));
                } else {
                  value = Number.parseInt(value)
                  if (value < 0 || value > 20000000000) {
                    callback(new Error('号码范围有误'))
                  } else {
                    callback()
                  }
                }
              }
            },
            trigger: 'blur'
          }
        ],
        exactAddr: [
          {
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('请输入确切地址'));
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  }
}
</script>

<style scoped>
.el-form-item {
  padding-right: 20px;
}
</style>